package com.jfinal.server.undertow;

import io.undertow.server.handlers.resource.Resource;
import io.undertow.server.handlers.resource.ResourceChangeListener;
import io.undertow.server.handlers.resource.ResourceManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * CompositeResourceManager
 */
public class CompositeResourceManager implements ResourceManager {
    protected final List<ResourceManager> resourceManagers = new ArrayList<>();

    public boolean isEmpty() {
        return resourceManagers.isEmpty();
    }

    public void add(ResourceManager resourceManager) {
        resourceManagers.add(resourceManager);
    }

    @Override
    public Resource getResource(String path) throws IOException {
        for (ResourceManager rm : resourceManagers) {
            Resource ret = rm.getResource(path);
            if (ret != null) {
                return ret;
            }
        }
        return null;
    }

    @Override
    public boolean isResourceChangeListenerSupported() {
        return resourceManagers.stream()
                .anyMatch(ResourceManager::isResourceChangeListenerSupported);
    }

    @Override
    public void registerResourceChangeListener(ResourceChangeListener listener) {
        resourceManagers.stream()
                .filter(ResourceManager::isResourceChangeListenerSupported)
                .forEach(resourceManager -> resourceManager.registerResourceChangeListener(listener));
    }

    @Override
    public void removeResourceChangeListener(ResourceChangeListener resourceChangeListener) {
        resourceManagers.stream()
                .filter(ResourceManager::isResourceChangeListenerSupported)
                .forEach(resourceManager -> resourceManager.removeResourceChangeListener(resourceChangeListener));
    }

    @Override
    public void close() throws IOException {
        for (ResourceManager rm : resourceManagers) {
            rm.close();
        }
    }
}








